class absolute_defense extends AcGameObject {
    constructor(playground, player, x, y, radius, vx, vy, color, alive_time, damage) {
        super();
        this.playground = playground;
        this.player = player;
        this.ctx = this.playground.game_map.ctx;
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.spent_time = 0;
        this.radius = radius;
        this.color = color;
        this.alive_time = alive_time;
        this.damage = damage;
        this.eps = 0.1;
    }

    start() {
    }

    update() {
        // if (this.move_length < this.eps) {
        //     this.destroy();
        //     return false;
        // }
        this.spent_time += this.timedelta / 1000;
        if (this.spent_time >= this.alive_time) {
            this.destroy();
            this.on_destory();
            return false;
        }
        let players_is_attacked = [];
        for (let i = 0; i < this.playground.players.length; i ++ ) {
            let player = this.playground.players[i];
            if (this.player !== player && this.is_collision(player)) {
                players_is_attacked.push(player);
            }
        }
        for (let i = 0; i < players_is_attacked.length; i ++ ) {
            this.attack(players_is_attacked[i]);
        }
        this.render();
    }

    get_dist(x1, y1, x2, y2) {
        let dx = x1 - x2;
        let dy = y1 - y2;
        return Math.sqrt(dx * dx + dy * dy);
    }

    is_collision(player) {
        let distance = this.get_dist(this.x, this.y, player.x, player.y);
        if (distance < this.radius + player.radius)
            return true;
        return false;
    }

    attack(player) {
        let angle = Math.atan2(player.y - this.y, player.x - this.x);
        player.is_attacked(angle, this.damage);
        // this.destroy();
    }
    on_destory() {
        for (let i = 0; i < this.player.absolute_defenses.length; i ++ ) {
            if (this.player.absolute_defenses[i] === this) {
                this.player.absolute_defenses.splice(i, 1);
            }
        }
    }
    render() {
        this.ctx.beginPath();
        this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        this.ctx.fillStyle = this.color;
        this.ctx.fill();
    }
}
